package cn.wegoteam.shop.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import cn.wegoteam.shop.action.BaseAction;
import cn.wegoteam.shop.cache.Cache;
import cn.wegoteam.shop.cache.StaticDataCache;
import cn.wegoteam.shop.inter.AddressServiceInter;
import cn.wegoteam.shop.inter.OrderServiceInter;
import cn.wegoteam.shop.inter.CartServiceInter;
import cn.wegoteam.shop.inter.PayImpServiceInter;
import cn.wegoteam.shop.inter.PayServiceInter;
import cn.wegoteam.shop.inter.ProductServiceInter;
import cn.wegoteam.shop.inter.UserServiceInter;
import cn.wegoteam.shop.po.Address;
import cn.wegoteam.shop.po.Order;
import cn.wegoteam.shop.po.Cart;
import cn.wegoteam.shop.po.Product;
import cn.wegoteam.shop.po.Staticdata;
import cn.wegoteam.shop.po.User;
import cn.wegoteam.shop.service.AlipayService;
import cn.wegoteam.shop.util.Const;
import cn.wegoteam.shop.util.MyString;
import cn.wegoteam.shop.util.PostAndGetRequset;

@ParentPackage("users")
@Namespace("/")
@Controller
public class OrderInteceptorAction extends BaseAction<Order> {
	
	private static final long serialVersionUID = -7214652284224332303L;
	@Autowired 
	private AddressServiceInter addressService;  
	@Autowired 
	private ProductServiceInter productService;
	@Autowired
	private OrderServiceInter orderService; 
	@Autowired
	private UserServiceInter userService; 
	@Autowired
	private CartServiceInter cartService;
	@Autowired
	private PayServiceInter payService;
	public String p_state;//订单状态
	@Action(value = "orderDetail")
	public void orderDetail(){
		model = orderService.get(model);
		StringBuilder content=new StringBuilder("<table class='table table-condensed table-bordered mb0 table-hover f12'>");
		if(model == null)
			content.append("<tr><td>抱歉，查询出错</td></tr>");
		else{
			String tr = "<tr><td>%s</td><td>%s</td></tr>";
			
			content.append(String.format(tr, "订单状态：",model.getStaticState().getName()+":"+model.getStaticState().getDescription()));
			content.append(String.format(tr, "收货人：",model.getAccepter()));
			content.append(String.format(tr, "收货地址：",model.getAddress()));
			content.append(String.format(tr, "快递：",model.getLogisticsName()));
			content.append(String.format(tr, "快递编号：",MyString.isEmpty(model.getLogisticsNum())?"":model.getLogisticsNum()));
			content.append(String.format(tr, "留言：",model.getMessage()));
		}
		content.append("</table>");
		writeStringToResponse(content.toString());
	}
	@Action(value = "logistics")
	public void logistics() throws Exception{
		model = orderService.get(model);
		if(model==null){
			writeStringToResponse("[ERROR]");
			return;
		}
		String content= PostAndGetRequset.Kuaidi("http://www.kuaidi100.com/query?type="+StaticDataCache.getStaticdata(model.getLogistics()).getDescription()+"&postid="+model.getLogisticsNum());  
		writeStringToResponse(content);
	}
	
	@Action(value = "confirmOrder", results = { @Result(name = "success", location = WEB
			+ "confirmOrder.jsp") })
	public String confirmOrder() {
			map.put("id|in", Cart.getProductIds());
			List<Product> ps =productService.getList(null, map);
			Map<String, Cart> cs = Cart.getCarts(ps);
			
			String[] ids = request.getParameterValues("p_id");
			if(ids == null){
				tipMessage="抱歉，连接已失效，请重新再试！";
				return ERROR;
			}
			List<Cart> csl = new ArrayList<Cart>();
			float total = 0.0f;
			for (String id : ids) {
				Cart c= cs.get(id);
				c.setNum(getParameter("p_num_"+id, 1));
				csl.add(c);
				total += c.getNum()*c.getProduct().getTruePrice();
			}
			session.put(Const.SESS_ORDERS, csl);
			
			map.clear();
			map.put("user.id", getSessionUser().getId());
			request.setAttribute("adds", addressService.getList(null, map, "def desc"));
			request.setAttribute("cs",csl);
			request.setAttribute("totalMoney", total);
			
			List<Staticdata> logistics = StaticDataCache.getStaticdatas("LOGISTICS","NO");
			request.setAttribute("logistics", logistics);
			
			Float freight = Float.parseFloat(logistics.get(0).getValue());
			
			if(total>Float.parseFloat(Cache.getSetting(Const.FREEOFLOGISTICS).getValue())){
				freight = 0F;
			}
			request.setAttribute("freight", freight);
			request.setAttribute("finallyPay",freight+total);
			return SUCCESS;
	}
	//扣除用户积分，在取消订单时候返回给用户，退款不返回积分，由管理人员手动解决
	//改变商品库存，在取消订单时恢复库存，退款不修改库存，由管理人员手动解决
	//系统不添加定时器自动取消超时订单，由管理人员在后台手动取消订单
	@Action(value = "submitOrder", results = { @Result(name = "success", type = "redirect", location = "pay?id=${model.id}")})
	public String submitOrder() {
				Address ad = addressService.get(getParameter("p_address",-1));
				StringBuilder sb = new StringBuilder();
				
				if(!orderService.save(model,getSessionUser(),cartService,session,sb,ad)){
					tipMessage="收货地址不能为空";
					return ERROR;
				}
				/**
				 * 添加至订单成功，删除购物车中的商品
				 * 删除购物车cookie，不能一个一个删，必须一起删除，因为cookie是从浏览器中传过来的
				 * 在一个request范围内所有cookie是一致的
				 */
				cartService.deleteFromCart(sb.toString().substring(0,sb.length()-1), session);
			request.setAttribute("id", model.getId());
			return SUCCESS;
	}
	@Action(value = "trade", results = { @Result(name = "success", location = ORDER
			+ "tradePage.jsp") })
	public String trade() {
			pageBean.setSize(2);
			map.put("user.id", getSessionUser().getId()+"");
			map.put("state", p_state);
			map.put("flag|>", 0);
			
			paramMap.put("state", p_state);
			models = orderService.getList(pageBean, map,"id desc");
			return SUCCESS;
	}
	/**
	 * 取消订单，删除订单，申请退款...
	 * @return
	 */
	@Action(value = "modifyOrder", results = { @Result(name = "success", location = ORDER
			+ "tradeDetail.jsp") })
	public String modifyOrder() {
			User u = getSessionUser();
			tipMessage = orderService.modifyOrder(model,u,getParameter("p_flag", 0),getParameter("p_state", ""));
			if(tipMessage!=null)
				return ERROR;
			putSessionUser(u);
			return SUCCESS;
	}
	
	/**
	 * 支付
	 */
	@Action(value = "pay",results={@Result(name="success",location=ORDER+"paySure.jsp"),@Result(name="error",location=WEB+"500.jsp")})
	public String alipay() {
		if (model.getId() == null){
			writeStringToResponse("抱歉，系统繁忙，请求失败！");
			return ERROR;
		}
		model = orderService.get(model);
		return SUCCESS;
		//注释的部分走真实的支付包流程的接口，暂时没有商家的支付宝账号，所以调转到假的支付宝页面
		//payService.pay(model, getSessionUser(), request);
	}
	@Action(value="paySuccess",results={@Result(name="success",type = "redirect",location="personCenter?p_action=trade")})
	public String paySuccess(){
		model.setState(Const.STATIC_PAID);
		orderService.updateBySql(model);
		return SUCCESS;
	}
	
	
	/**
	 * 支付宝回调
	 */
	@Action(value = "alipayReturn")
	public String alipayReturn() {
		PayImpServiceInter payImpService = new AlipayService();
		pageTitle=payImpService.payReturn(payService,request);
		return SUCCESS;
	}
	public String getP_state() {
		return p_state;
	}
	public void setP_state(String p_state) {
		this.p_state = p_state;
	}
	
}
